<template>
  <div>
    <el-tabs v-model="searchForm.tab" class="demo-tabs" @tab-change="getData">
      <el-tab-pane
        v-for="(item, index) in tabbars"
        :key="index"
        :label="item.name"
        :name="item.key"
      />
    </el-tabs>

    <el-card shadow="never" class="border-0">
      <Search @search="getData" @reset="resetSearchForm" :model="searchForm">
        <search-item label="关键词" prop="title">
          <el-input
            v-model="searchForm.title"
            placeholder="商品名称"
            clearable
          />
        </search-item>
        <template #show>
          <search-item label="商品分类" prop="category_id">
            <el-select
              v-model="searchForm.category_id"
              placeholder="请选择商品分类"
              clearable
            >
              <el-option
                v-for="item in category_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </search-item>
        </template>
      </Search>

      <list-header
        layout="create,refresh"
        @create="handleCreate"
        @refresh="getData"
      >
        <el-button
          size="small"
          @click="handleMultiDelete"
          type="danger"
          v-if="searchForm.tab !== 'delete'"
        >
          批量删除
        </el-button>

        <el-button
          size="small"
          @click="handleRestoreGoods"
          type="warning"
          v-else
        >
          恢复商品
        </el-button>

        <el-popconfirm
          v-if="searchForm.tab == 'delete'"
          title="是否要彻底删除该商品？ "
          confirmButtonText="确认"
          cancelButtonText="取消"
          @confirm="handleDestoryGoods"
        >
          <template #reference>
            <el-button class="p-1" type="danger" size="small">
              彻底删除
            </el-button>
          </template>
        </el-popconfirm>

        <el-button
          size="small"
          @click="handleMultiStatusChange(1)"
          v-if="searchForm.tab == 'all' || searchForm.tab == 'off'"
        >
          上架
        </el-button>
        <el-button
          size="small"
          @click="handleMultiStatusChange(0)"
          v-if="searchForm.tab == 'all' || searchForm.tab == 'saling'"
        >
          下架
        </el-button>
      </list-header>

      <el-table
        ref="multipleTableRef"
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品" width="300">
          <template #default="{ row }">
            <div class="flex">
              <el-image
                :src="row.cover"
                fit="cover"
                :lazy="true"
                style="width: 50px; height: 50px"
                class="mr-3 rounded"
              />
              <div class="flex-1">
                <p>{{ row.title }}</p>
                <div>
                  <span class="text-rose-500">￥{{ row.min_price }}</span>
                  <el-divider direction="vertical" />
                  <span class="text-gray-500 text-xs">
                    ￥{{ row.min_price }}
                  </span>
                </div>
                <p class="text-gray-400 text-xs mb-1">
                  分类：{{ row.category ? row.category.name : '未分类' }}
                </p>
                <p class="text-gray-400 text-xs">
                  创建时间：{{ row.create_time }}
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实际销量" width="80" prop="sale_count" />
        <el-table-column label="商品状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'" size="small">
              {{ row.status ? '上架' : '仓库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="审核状态"
          width="120"
          align="center"
          v-if="searchForm.tab !== 'delete'"
        >
          <template #default="{ row }">
            <div class="flex flex-col" v-if="row.ischeck === 0">
              <el-button type="success" size="small" plain>审核通过</el-button>
              <el-button class="mt-2 !ml-0" type="danger" size="small" plain>
                审核拒绝
              </el-button>
            </div>
            <span v-else>
              {{ row.ischeck === 1 ? '通过' : '拒绝' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="总库存" width="90" prop="stock" />
        <el-table-column label="操作">
          <template #default="scope">
            <div v-if="searchForm.tab !== 'delete'">
              <el-button
                class="p-1"
                type="primary"
                size="small"
                text
                @click="handleEdit(scope.row)"
              >
                修改
              </el-button>
              <el-button
                class="p-1"
                :type="(scope.row.sku_type == 0 && !scope.row.sku_value) 
                  || (scope.row.sku_type == 1 && !scope.row.goods_skus.length) ? 'danger' : 'primary'"
                size="small"
                text
                :loading="scope.row.skusLoading"
                @click="handleSetGoodsSkus(scope.row)"
              >
                商品规格
              </el-button>
              <el-button
                class="p-1"
                :type="
                  scope.row.goods_banner.length === 0 ? 'danger' : 'success'
                "
                size="small"
                text
                :loading="scope.row.bannersLoading"
                @click="handleSetGoodsBanners(scope.row)"
              >
                设置轮播图
              </el-button>

              <el-button
                class="p-1"
                :type="scope.row.content ? 'success' : 'danger'"
                size="small"
                text
                :loading="scope.row.contentLoading"
                @click="handleSetGoodsContent(scope.row)"
              >
                商品详情
              </el-button>
              <el-popconfirm
                title="是否要删除该商品？ "
                confirmButtonText="确认"
                cancelButtonText="取消"
                @confirm="handleDelete([scope.row.id])"
              >
                <template #reference>
                  <el-button class="p-1" type="primary" size="small" text>
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>

            <span v-else>暂无操作</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex items-center justify-center mt-5">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="limit"
          @current-change="getData"
        />
      </div>

      <FormDrawer
        ref="formDrawerRef"
        :title="drawerTitle"
        @submit="handleSumbit"
        @cancel="handleCancel"
      >
        <el-form
          :model="form"
          ref="formRef"
          :rules="rules"
          label-width="120px"
          :inline="false"
        >
          <el-form-item label="商品名称" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入商品名称，不能超过60个字符"
            />
          </el-form-item>
          <el-form-item label="封面" prop="cover" ref="chooseImageUploadRef">
            <choose-image v-model="form.cover" @upImgSuc="handleUpImgSuc" />
          </el-form-item>
          <el-form-item label="商品分类" prop="category_id">
            <el-select
              v-model="form.category_id"
              placeholder="请选择所属商品分类"
            >
              <el-option
                v-for="item in category_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品描述" prop="desc">
            <el-input
              v-model="form.desc"
              placeholder="请输入商品描述"
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input
              v-model="form.unit"
              placeholder="请输入单位"
              style="width: 50%"
            />
          </el-form-item>
          <el-form-item label="总库存" prop="stock">
            <el-input type="number" v-model="form.stock" style="width: 40%">
              <template #append>件</template>
            </el-input>
          </el-form-item>
          <el-form-item label="库存预警" prop="min_stock">
            <el-input
              type="number"
              v-model="form.min_stockv"
              style="width: 40%"
            >
              <template #append>件</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低销售价" prop="min_price">
            <el-input type="number" v-model="form.min_price" style="width: 40%">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低原价" prop="min_oprice">
            <el-input
              type="number"
              v-model="form.min_oprice"
              style="width: 40%"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="库存显示" prop="stock_display">
            <el-radio-group v-model="form.stock_display">
              <el-radio :label="0"> 显示 </el-radio>
              <el-radio :label="1"> 隐藏 </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否上架" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="0"> 放入仓库 </el-radio>
              <el-radio :label="1"> 立即上架 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </FormDrawer>

      <!-- 设置轮播图 -->
      <Banners ref="bannersRef" @reloadData="getData" />
      <!-- 设置商品详情 -->
      <Content ref="contentRef" @reloadData="getData" />
      <!-- 设置商品规格 -->
      <Skus ref="skusRef" @reloadData="getData" />
    </el-card>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import {
    getGoodsListApi,
    updateGoodsStatusApi,
    createGoodsApi,
    updateGoodsApi,
    deleteGoodsApi,
    restoreGoodsApi,
    destroyGoodsApi,
  } from '@/api/goods.js'
  import { getCategoryListApi } from '@/api/category.js'
  import FormDrawer from '@/components/FormDrawer.vue'
  import ChooseImage from '@/components/ChooseImage.vue'
  import ListHeader from '@/components/ListHeader.vue'
  import Search from '@/components/Search.vue'
  import SearchItem from '@/components/SearchItem.vue'
  import Banners from './banners.vue'
  import Content from './content.vue'
  import Skus from './skus.vue'
  import { useInitTable, useInitForm } from '@/hooks/useCommon.js'
  import { toast } from '@/utils'

  const {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
    handleSelectionChange,
    handleMultiStatusChange,
    handleMultiDelete,
    multipleTableRef,
    multiSelectionIds
  } = useInitTable({
    // 搜索需要的参数
    searchForm: {
      title: '',
      tab: 'all',
      categoryId: null,
    },
    // 获取表单的api
    getlist: getGoodsListApi,
    delete: deleteGoodsApi,
    updateStatus: updateGoodsStatusApi,
    // 获取表单成功的回调
    onGetListSuccess: (res) => {
      tableData.value = res.list.map((o) => {
        o.bannersLoading = false
        o.contentLoading = false
        o.skusLoading = false
        return o
      })
      total.value = res.totalCount
    },
  })

  // 删除商品恢复
  function handleRestoreGoods() {
    useMultiAction(restoreGoodsApi, '恢复')
  }

  // 彻底删除
  function handleDestoryGoods() {
    useMultiAction(destroyGoodsApi, '恢复')
  }

  function useMultiAction(func, msg) {
    loading.value = true
    func(multiSelectionIds.value)
      .then(res => {
        toast(msg + '成功')
        if(multipleTableRef.value) {
          multipleTableRef.value.clearSelection()
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  const {
    formDrawerRef,
    formRef,
    form,
    rules,
    drawerTitle,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  } = useInitForm({
    form: {
      title: null, //商品名称
      category_id: null, //商品分类
      cover: null, //商品封面
      desc: null, //商品描述
      unit: '件', //商品单位
      stock: 100, //总库存
      min_stock: 10, //库存预警
      status: 1, //是否上架 0仓库1上架
      stock_display: 1, //库存显示 0隐藏1显示
      min_price: 0, //最低销售价
      min_oprice: 0, //最低原价
    },
    rules: {},
    getData,
    create: createGoodsApi,
    update: updateGoodsApi,
  })

  // 上传图片成功
  const chooseImageUploadRef = ref(null)
  function handleUpImgSuc() {
    chooseImageUploadRef.value.clearValidate()
  }

  const tabbars = [
    { key: 'all', name: '全部' },
    { key: 'checking', name: '审核中' },
    { key: 'saling', name: '出售中' },
    { key: 'off', name: '已下架' },
    { key: 'min_stock', name: '库存预警' },
    { key: 'delete', name: '回收站' },
  ]

  // 商品分类
  const category_list = ref([])
  getCategoryListApi().then((res) => (category_list.value = res))

  // 设置轮播图
  const bannersRef = ref(null)
  function handleSetGoodsBanners(row) {
    bannersRef.value.open(row)
  }

  // 设置商品详情
  const contentRef = ref(null)
  function handleSetGoodsContent(row) {
    contentRef.value.open(row)
  }

  // 设置商品规格
  const skusRef = ref(null)
  function handleSetGoodsSkus(row) {
    skusRef.value.open(row)
  }
</script>

<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
